import { Form, Select, Input, Button, Spin } from 'antd';
import React from 'react';
import request from '@/utils/request';
import _ from 'lodash';

const { Option } = Select;
@Form.create()
export default class Login extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      spinning: false,
    };
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          spinning: true,
        });
        let params = {};
        let data = {};
        if (values.type === 'GET' || values.type === 'DELETE') {
          params = JSON.parse(values.parameters);
        } else {
          data = values.parameters;
        }
        // console.log(JSON.parse(params), 'params');
        // console.log(data, 'data');
        request(values.url, {
          method: values.type,
          params,
          data,
        }).then(data => {
          this.setState({
            data,
            spinning: false,
          });
        });
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { spinning } = this.state;
    return (
      <Spin tip="Loading..." spinning={spinning}>
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 12 }} onSubmit={this.handleSubmit}>
          <Form.Item label="url">
            {getFieldDecorator('url', {
              initialValue: '',
              rules: [{ required: true, message: 'Please input your url!' }],
            })(<Input placeholder="managementValue/attribute" />)}
          </Form.Item>
          <Form.Item label="type">
            {getFieldDecorator('type', {
              initialValue: 'GET',
            })(
              <Select placeholder="type">
                <Option value="GET">GET</Option>
                <Option value="POST">POST</Option>
                <Option value="PUT">PUT</Option>
                <Option value="DELETE">DELETE</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="parameters">
            {getFieldDecorator('parameters', {
              initialValue: '',
            })(<Input placeholder='格式示例：{"name":"小明"}' />)}
          </Form.Item>
          {!_.isEmpty(this.state.data) ? (
            <Form.Item label="报文">
              <Input.TextArea value={JSON.stringify(this.state.data)} placeholder="response" />
            </Form.Item>
          ) : null}
          <Form.Item wrapperCol={{ span: 12, offset: 5 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Spin>
    );
  }
}
